
YUI.add('xWidget-img', function( Y ){	

		var defConfig = {
			targetId:'',
			maxWH:[50,50],
			isZoom:true
		};
	
		var img = function(){
		};

		Y.mix( img.prototype, {
			
			init:function( userConfig ){
				this._config = Y.merge( defConfig, userConfig || {} );				
				this.bindUI();

				return this;
			},
			
			bindUI:function(){
				this._dTarget = Y.DOM.get( this._config.targetId );
				this._loading = false;
			},

			_getOriginalWH:function( imgSrc, oCallBack ){				
				var img 	= new Image();
				var _self = this;

				this._loading = true;				
				img.onload = function(){
					oCallBack.call( _self, this.width, this.height );
					img.onload= null;
					img = null;
					this._loading = false;
				};
				img.src = imgSrc;
			},
			
			replaceImg:function( imgSrc, oConfig ){
				this._dTarget.src = imgSrc;
				if( (oConfig && oConfig.isZoom) || this._config.isZoom ){
					this.setMaxSize( this._config.maxWH[0], this._config.maxWH[1] );
				};
				return this;
			},

			setMaxSize:function( maxWidth, maxheight ){
				var _self = this;
				
				this._getOriginalWH( this._dTarget.src, function(w,h){
					var dW = maxWidth/w,
							dH = maxheight/h,
							d	 = (dW<=dH ? dW : dH ),
							newWidth,
							newHeight;

					if( d>=1 ){ return ; }
					newWidth	= (ET.UA.ie ? parseInt(w*d) : parseInt(w*d)+'px');
					newHeight = (ET.UA.ie ? parseInt(h*d) : parseInt(h*d)+'px');

					this.setAttr( { 'width':newWidth, 'height':newHeight } );
				});
				
				return this;
			},
			
			setAttr:function( oConfig ){
				this._setAttr( this._dTarget, oConfig );
				return this;
			},
			
			_setAttr:function( el, oConfig ){
				for( var proto in oConfig ){
					el.setAttribute( proto, oConfig[proto] );
				}
			}
		});
		
		Y.xWidget.img = img;
}, '1.0', {requires:['dom-base']});
